package com.xiaoxie.cloud.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.xiaoxie.cloud.entities.PayDTO;
import com.xiaoxie.cloud.resp.ResultData;
import com.xiaoxie.cloud.resp.ReturnCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

@RestController
@Slf4j
public class PayAlibabaController {

    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/pay/nacos/{id}")
    public String getPayInfo(@PathVariable("id") Integer id) {
        return "nacos registry, serverPort: "+ serverPort + "\t id" + id;
    }

    // openfeign + sentinel进行服务降级和流量监控的整合处理case
    @GetMapping("/pay/nacos/get/{orderNo}")
    @SentinelResource(value = "getPayOrderNo",blockHandler = "handlerBlockHandler")
    public ResultData getPayOrderNo(@PathVariable("orderNo") String orderNo) {
        // 模拟从数据库查询出来数据并赋值给DTO
        PayDTO payDTO = new PayDTO();
        payDTO.setId(1024);
        payDTO.setOrderNo(orderNo);
        payDTO.setAmount(new BigDecimal("100.00"));
        payDTO.setPayNo("pay:" + IdUtil.fastUUID());
        payDTO.setUserId(1);
        return ResultData.success("查询成功", payDTO);
    }
    private ResultData handlerBlockHandler(String orderNo, BlockException e) {
        return ResultData.fail(ReturnCodeEnum.RC500.getCode(), "getPayOrderNo服务不可用，触发sentinel流控配置规则！！");
    }
}
